
const uuidv1 = require('uuid/v1');
var moment = require('./moment');
var socket = require('./socket');
var Account = require('../mongoose/account');
var Friends = require('../mongoose/friends');
var AddFriends = require('../mongoose/addFriends');
var Messages = require('../mongoose/messages');
var Unread = require('../mongoose/unread');
var Member = require('../mongoose/member');

module.exports = {
  register(req, res, next) {
    let { account, password } = req.body
    // 先查有没有注册过
    Account.findOne({ account }).then(response => {
      // 账号已经被注册
      if (response) return res.send({ code: '002', msg: '已经被注册' });
      // 账号未被注册
      let uuid = uuidv1()
      Account.create({
        account, password, uuid,
        userName: account,
        avat: 'http://localhost:3000/images/man.png'
      }).then((response) => {
        res.send({ code: '001', msg: 'success', uuid });
      })
    })

  },
  login(req, res, next) {
    let { account, password } = req.body
    // 先查有没有注册过
    Account.findOne({ account }).then(response => {
      // 账号未被注册
      if (!response) return res.send({ code: '002', msg: '账号或密码错误' });
      // 账号已经被注册
      if (response.account === account && response.password === password) {
        res.send({ code: '001', msg: 'success', uuid: response.uuid })
      }else{
        res.send({ code: '002', msg: '账号或密码错误' })
      }
    })

  },
  async recentChat(req, res, next) {
    let { uuid } = req.body
    let recentChats = await Member.aggregate(
      [
        {
          $match: {
            $or: [{
              'member.0': uuid
            },
            {
              'member.1': uuid
            }]
          }
        },
        {
          $lookup:
          {
            from: "messages",
            localField: "roomId",
            foreignField: "roomId",
            as: "messages",
          }
        },
        {
          $lookup:
          {
            from: "accounts",
            localField: "member",
            foreignField: "uuid",
            as: "accounts",
          }
        },
        {
          $lookup:
          {
            from: "unreads",
            localField: "roomId",
            foreignField: "roomId",
            as: "unreads",
          }
        }
      ]
    )
    res.send(recentChats)

  },
  async getUserChatRecord(req, res, next) {
    let { uuid, roomId, page } = req.body
    if (roomId) {
      let messages = await Messages.aggregate([
        {
          $match: {
            roomId
          }
        },
        {
          $lookup:
          {
            from: "accounts",
            localField: "uuid",
            foreignField: "uuid",
            as: "accounts",
          }
        }
      ]).sort({ time: -1 }).skip(page * 5).limit(5).sort({ time: 1 })
      messages.forEach(item => {
        item.avat = item.accounts[0].avat
      })
      res.send(messages)
    } else {
      let messages = await Member.aggregate([
        {
          $match: {
            'member.0': {
              $in: uuid
            },
            'member.1': {
              $in: uuid
            },
          }
        },
        {
          $lookup:
          {
            from: "messages",
            localField: "roomId",
            foreignField: "roomId",
            as: "messages",
          }

        },
        {
          $lookup:
          {
            from: "accounts",
            localField: "messages.uuid",
            foreignField: "uuid",
            as: "accounts",
          }

        }
      ])
      if (!messages[0]) return res.send([])
      messages[0].messages.forEach(item => {
        let that = messages[0].accounts.find(it => it.uuid === item.uuid)
        item.avat = that.avat
      })
      res.send(messages[0].messages)

    }
    // 修改这个用户的未读时间
    let time = Date.now()
    let findOneAndUpdate = await Unread.findOneAndUpdate({
      roomId, 'unread.uuid': uuid[0]
    }, { 'unread.$.time': time })
    // 新增这个用户的未读数据
    if (!findOneAndUpdate) await Unread.findOneAndUpdate({
      roomId
    }, {
      $addToSet: {
        unread: {
          uuid:uuid[0], time
        }
      }
    })
  },
  getUserName(req, res, next) {
    let { uuid } = req.body
    // 先查有没有注册过
    Account.findOne({ uuid }).then(response => {
      // 账号未被注册
      if (!response) return res.send({ code: '002', msg: '用户不存在' });
      // 账号已经被注册
      res.send(response)
    })

  },
  changeName(req, res, next) {
    let { uuid, userName } = req.body
    // 先查有没有注册过
    Account.findOneAndUpdate({ uuid, userName }).then(response => {
      res.send({ code: '001', msg: 'success' })
    })

  },
  getUserName_list(req, res, next) {
    let { uuid } = req.body
    // 先查有没有注册过
    Account.find({
      uuid: {
        $in: uuid
      }
    }).then(response => {
      // 账号未被注册
      if (!response) return res.send({ code: '002', msg: '用户不存在' });
      // 账号已经被注册
      res.send(response)
    })

  },
  async getUserName_state(req, res, next) {
    let { uuid, other } = req.body
    // 先查有没有注册过
    let account = await Account.findOne({ uuid: other }).lean()
    // 账号未被注册
    if (!account) return res.send({ code: '002', msg: '用户不存在' });
    // 账号已经被注册
    let addFriends = await AddFriends.findOne(
      { other: uuid, uuid: other }
    )
    if (addFriends) account.state = addFriends.state
    res.send(account)

  },
  async getNewFriends(req, res, next) {
    let { uuid } = req.body
    // 先查有没有注册过
    let addFriends = await AddFriends.find({
      $or: [
        { uuid },
        { other: uuid }
      ]
    }).lean()
    let findList = addFriends.map(item => item.uuid === uuid ? item.other : item.uuid)
    let accounts = []
    for (let i = 0; i < findList.length; i++) {
      accounts.push(await Account.findOne({
        uuid: findList[i]
      }).lean())
    }
    accounts.forEach((item, index) => {
      Object.assign(accounts[index], addFriends[index])
      item.time = moment(item.time).fromNow()
    })
    res.send(accounts)
  },
  addFriends_list(req, res, next) {
    let { uuid } = req.body
    // 先查有没有注册过
    Account.find().then(response => {
      res.send(response)
    })

  },
  getAddFriend(req, res, next) {
    let { uuid } = req.body
    // 先查有没有注册过
    AddFriends.find({
      other: uuid, state: 0
    }).then(response => {
      res.send(response)
    })

  },

  async addFriend_request(req, res, next) {
    let { initiator,
      saySomething,
      inviter } = req.body
    let time = Date.now()
    // 先查
    let addFriends = await AddFriends.findOne({
      other: inviter,
      uuid: initiator,
      state: 0
    })
    if (addFriends) {
      await AddFriends.findOneAndUpdate({
        other: inviter,
        uuid: initiator,
        state: 0
      }, {
        time, saySomething
      })
    } else {
      await AddFriends.create({
        uuid: initiator,
        saySomething,
        other: inviter,
        state: 0,
        time
      })
    }
    // socket通知该用户
    socket.notifyManyPeople([inviter], JSON.stringify({
      type: 'addfriend'
    }))
    res.send({ code: '001', msg: 'success' })
  },
  async addFriend_agree(req, res, next) {
    let { uuid, other } = req.body
    // 修改加好友的状态
    let addFriends = await AddFriends.findOneAndUpdate({ uuid: other, other: uuid }, { state: 1 })
    if (!addFriends) res.send({ code: '002', msg: 'fail' })
    // 添加好友到好友列表
    await Friends.create({
      friend1: uuid,
      friend2: other
    })
    res.send({ code: '001', msg: 'success' })
  },
  async getUserFriends(req, res, next) {
    let { uuid } = req.body
    // 修改加好友的状态
    let addFriends = await Friends.find({
      $or: [
        {
          friend1: uuid
        },
        {
          friend2: uuid
        }
      ]
    }).lean()
    if (!addFriends) return res.send([])
    let friendsList = addFriends.map(item => item.friend1 === uuid ? item.friend2 : item.friend1)
    let account = await Account.find({
      uuid: {
        $in: friendsList
      }
    })
    res.send(account)
  },
  uploadFile(req, res) {
    let { roomId, uuid, other } = req.body
    res.send('http://127.0.0.1:3000' + req.file.path.replace(/\\/g, '/').replace('public', ''))
  }

}